package com.solocredit.finance.mvp

import android.view.View
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.BaseActivity
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.databinding.IncludeMullaLicenseViewBinding
import com.solocredit.finance.ui.splash.act.MullaSplashAct
import com.solocredit.finance.utils.dialog.KefuDialog
import com.solocredit.finance.utils.dialog.LanguageDialog
import com.solocredit.finance.utils.dialog.NetworkErrorDialog
import com.solocredit.finance.utils.dialog.NetworkErrorDialog.IDialogCallback
import com.solocredit.finance.utils.dialog.TipsDialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaSubscriber
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/30 18:54
 * @Annotation：
 */
abstract class ProAct: BaseActivity(), MullaSubscriber, CoroutineScope by MainScope() {

    /* 网络异常重试回调列表 */
    private val retryCallbacks = mutableSetOf<() -> Unit>()
    private var networkDialog: NetworkErrorDialog? = null
    private var showErrorCount = 0

    override fun onStart() {
        super.onStart()
        MyApp.app.publisher.register(this)
    }

    /**
     * 客服
     */
    fun showMullaKefuDialog(eventRemark: String = "",pName: String = "",pToken: String = ""){
        KefuDialog(this)
            .setMullaCancelable(true)
            .setMullaCanceledOnTouchOutside(true)
            .setMullaKefuPName(pName)
            .setMullaKefuPToken(pToken)
            .setMullaKefuRemark(eventRemark)
            .setMullaKefuCallback(object : KefuDialog.IDialogCallback{
                override fun onClick(view: View?) {
                }
            })
            .show()
    }

    /**
     * 错误提示
     */
    fun showMullaErrorTipsDialog(tips: String,eventRemark: String = ""){
        val tipsDialog = TipsDialog(this,eventRemark,object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {

            }
        })
        tipsDialog.show()
        tipsDialog.setTips(tips)
    }

    /**
     * 语言切换
     */
    fun showMullaLanguageDialog(eventRemark: String,isCancel: Boolean = true,isCancelTouch: Boolean = true,onSelectCallback: () -> Unit) {
        val languageDialog = LanguageDialog(this, eventRemark, object : LanguageDialog.IDialogCallback {
            override fun onMullaLanguageConfirmClick(isRestart: Boolean) {
                if (isRestart) {
                    // 我们可以充分运用 Activity 跳转动画，在跳转的时候设置一个渐变的效果
                    onIntent(MullaSplashAct::class.java)
                    overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
                    finish()
                } else {
                    onSelectCallback.invoke()
                }
            }
        })
        languageDialog.setCancelable(isCancel)
        languageDialog.setCanceledOnTouchOutside(isCancelTouch)
        languageDialog.show()
    }

    /**
     * 网络错误提示
     */
    override fun showMullaNetworkErrorDialog(eventRemark: String, onRetryClick: () -> Unit) {
        // 将回调添加到列表
        retryCallbacks.add(onRetryClick)
        if (networkDialog == null){
            networkDialog = NetworkErrorDialog(this,eventRemark,object : IDialogCallback{
                override fun onMullaRetryClick() {
                    // 执行所有缓存的回调
                    retryCallbacks.forEach { it.invoke() }
                    // 清空列表
                    retryCallbacks.clear()
                }
            })
            networkDialog?.setCancelable(false)
            networkDialog?.setCanceledOnTouchOutside(false)
        }
        if (isFinishing || isDestroyed){
            return
        }
        var errorMsg = getString(R.string.tips_network_error_failed)
        if (showErrorCount > 2){
            errorMsg = getString(R.string.tips_network_error_check)
        }
        networkDialog?.let { dialog ->
            if (dialog.isShowing){
                return
            }
            showErrorCount += 1
            dialog.show()
            dialog.setTips(errorMsg)
        }
    }

    /**
     * 获取当前用户VIP等级
     */
    fun getMullaUserVip(): Int{
        return MullaCustomConfigsHelper.getMullaUserVip()
    }

    /**
     * 获取用户当前积分数 (从签到信息中获取)
     */
    fun getMullaUserPoints(): Int{
        val signInfoString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_SIGN_INFO)
        if (signInfoString.isNotEmpty()){
            val signInfo = JSONObject(signInfoString)
            return signInfo.optInt("currScore")
        }
        return 0
    }

    /**
     * 获取当前用户优惠券数量（从优惠券列表获取）
     */
    fun getMullaUserCouponCount(): Int{
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_USER_COUPON_INFO)
        if (dataString.isEmpty()){
            return 0
        }
        val couponList = JSONArray(dataString)
        return couponList.length()
    }

    /**
     * 牌照信息View
     */
    fun licenseView(): View{
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo != null){
            val binding = IncludeMullaLicenseViewBinding.inflate(layoutInflater)
            ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
            return binding.root
        }
        return View(this)
    }

    /**
     * 处理订阅事件
     */
    override fun onMullaEvent(event: MullaEventData) {

    }

    override fun onDestroy() {
        super.onDestroy()
        networkDialog?.dismiss()
        networkDialog = null
        retryCallbacks.clear()
        MyApp.app.publisher.detach(this)
    }
}